package com.diyunapp.xilinapp.me;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.DaiJinQuanBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.diyunapp.xilinapp.utils.AbDateUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.BindColor;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DaiJinQuanActivity extends StatusBarFragmentActivity {

    @Bind(R.id.go_back)
    ImageView goBack;
    @Bind(R.id.daijinquan_fresh_lv)
    ListView daijinquanFreshLv;
    @Bind(R.id.daijinquan_refresh_view)
    SwipeRefreshLayout daijinquanRefreshView;

    private LayoutInflater inflater;
    private VoucherAdapter voucherAdapter;
    private List<DaiJinQuanBean.DateBean> info = new ArrayList<>();
    private String username;
    private View headView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getTopBar().setTitle("交易记录");
        setContentView(R.layout.activity_dai_jin_quan);
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        voucherAdapter = new VoucherAdapter(this);
        headView = findViewById(R.id.daijin_menubar_inc);
        super.MenuWidget(headView);

        ButterKnife.bind(this);
        initView();
        initDaiJinQuan();
        daijinquanFreshLv.setAdapter(voucherAdapter);


    }

    private void initView() {
        daijinquanRefreshView.setColorSchemeColors(R.color.domain_orange, R.color.green,
                R.color.blue, R.color.yellow);

        daijinquanRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "myordersSwiperefreshlayout onRefresh...");
                initDaiJinQuan();
            }
        });
        daijinquanRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("onRefresh", "invoke onRefresh...");
                if(MainActivity.myLogin.isLoginState())
                {
                    initDaiJinQuan();
                }
                else
                {
                    toast("您还没有登录！");
                    daijinquanRefreshView.setRefreshing(false);
                }
            }
        });
    }

    private void initDaiJinQuan() {
        String url = "" + MainActivity.url + "act=goods&op=voucher&username=" + MainActivity.myLogin.getUsername() + "";

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(10000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        daijinquanRefreshView.setRefreshing(false);
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");

                            if (result == 200) {
                                JSONArray listArray = resultObject.optJSONArray("date");
                                info.clear();
                                for (int i = 0; i < listArray.length(); i++) {
                                    JSONObject recordObject = listArray.optJSONObject(i);
                                    String voucher_id = recordObject.optString("voucher_id");
                                    long voucher_start_date = recordObject.optLong("voucher_start_date");
                                    long voucher_end_date = recordObject.optLong("voucher_end_date");
                                    String voucher_price = recordObject.optString("voucher_price");
                                    String voucher_limit = recordObject.optString("voucher_limit");
                                    String voucher_state = recordObject.optString("voucher_state");
                                    String store_name = recordObject.optString("store_name");

//                                    voucherAdapter.info.clear();
                                    info.add(new DaiJinQuanBean.DateBean(voucher_id, voucher_start_date, voucher_end_date, voucher_price,
                                            voucher_limit, voucher_state, store_name));
                                }
                                voucherAdapter.setList(info);
                                voucherAdapter.notifyDataSetChanged();

                            } else {
                                toast("当前暂无数据");
                                daijinquanRefreshView.setVisibility(View.GONE);

                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();
                            daijinquanRefreshView.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        daijinquanRefreshView.setRefreshing(false);
                        toast("请求失败");
                        daijinquanRefreshView.setVisibility(View.GONE);
                    }
                });
    }

    @OnClick(R.id.go_back)
    public void onClick() {
        finish();
    }

    class VoucherAdapter extends BaseAdapter {
        private List<DaiJinQuanBean.DateBean> info = new ArrayList<DaiJinQuanBean.DateBean>();
        private Context context;

        public VoucherAdapter(Context context) {
            super();
            this.context = context;
        }

        public void setList(List<DaiJinQuanBean.DateBean> list) {
            this.info = list;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return null == info ? 0 : info.size();
        }

        @Override
        public Object getItem(int position) {
            return null == info ? null : info.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        private ViewHolder viewHolder;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (null == convertView) {
                convertView = inflater.inflate(R.layout.item_daijinquan, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            DaiJinQuanBean.DateBean bean = info.get(position);
            viewHolder.youhuiMoney.setText("¥" + bean.getVoucher_price());
            viewHolder.youhuiShop.setText(bean.getStore_name());
            viewHolder.youhuiEdu.setText("店铺满" + bean.getVoucher_limit() + "元使用");
            String startTime = AbDateUtil.getStringByFormat(bean.getVoucher_start_date() * 1000, "yyyy-MM-dd");
            String endTime = AbDateUtil.getStringByFormat(bean.getVoucher_end_date() * 1000, "yyyy-MM-dd");
            viewHolder.youhuiTime.setText(startTime + "—" + endTime);
            if (bean.getVoucher_state() == "1" || bean.getVoucher_state().equals("1")) {
                viewHolder.youhuiState.setImageResource(R.drawable.zhong);
                viewHolder.rel_back.setBackgroundColor(Color.parseColor("#fff3ca"));
                viewHolder.imageView2.setVisibility(View.GONE);
            } else if (bean.getVoucher_state() == "2" || bean.getVoucher_state().equals("2")) {
                viewHolder.youhuiState.setImageResource(R.drawable.gray);
                viewHolder.imageView2.setImageResource(R.drawable.shi);
                viewHolder.rel_back.setBackgroundColor(viewHolder.gery);

            } else if (bean.getVoucher_state() == "3" || bean.getVoucher_state().equals("3")) {
                viewHolder.youhuiState.setImageResource(R.drawable.gray);
                viewHolder.rel_back.setBackgroundColor(viewHolder.gery);
                viewHolder.imageView2.setImageResource(R.drawable.guoqi);
            } else {
                viewHolder.rel_back.setBackgroundColor(viewHolder.gery);
            }
            return convertView;
        }


        class ViewHolder {
            @Bind(R.id.youhui_state)
            ImageView youhuiState;
            @Bind(R.id.youhui_money)
            TextView youhuiMoney;
            @Bind(R.id.youhui_shop)
            TextView youhuiShop;
            @Bind(R.id.youhui_edu)
            TextView youhuiEdu;
            @Bind(R.id.youhui_time)
            TextView youhuiTime;
            @Bind(R.id.imageView2)
            ImageView imageView2;
            @Bind(R.id.rel_back)
            RelativeLayout rel_back;
            @BindColor(R.color.youhuijuan)
            int color;
            @BindColor(R.color.youhuigrey)
            int gery;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }
}
